﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using CodeCamp.BL.Model;

namespace CodeCamp.BL
{
	public partial class CodeCampBL
	{
		
		#region Member Profile

		/// <summary>
		/// Gets the member profile with photo if available.
		/// </summary>
		/// <param name="userID">The user ID.</param>
		/// <returns></returns>
		public static MemberProfile GetMemberProfile(Guid userID)
		{
			using (var context = new CodeCampEntities())
			{
				MemberProfile result = context.MemberProfiles.Include("Attachment").FirstOrDefault(p => p.UserId == userID);
				return result;
			}
		}

		public static void SaveMemberProfile(MemberProfile memberProfile)
		{
			if (memberProfile == null)
			{
				return;
			}

			using (var context = new CodeCampEntities())
			{
				MemberProfile existing = context.MemberProfiles.FirstOrDefault(p => p.UserId == memberProfile.UserId);

				if (existing == null)
				{
					context.AddObject("MemberProfiles", memberProfile);
				}
				else
				{
					existing.AllowAnonymizedContact = memberProfile.AllowAnonymizedContact;
					existing.AllowPublicProfile = memberProfile.AllowPublicProfile;
					existing.Bio = memberProfile.Bio;
					existing.EmailOptIn = memberProfile.EmailOptIn;
					existing.FirstName = memberProfile.FirstName;
					existing.LastName = memberProfile.LastName;
				}
				context.SaveChanges();
			}
		}

		public static void SaveMemberPhoto(HttpPostedFileBase photo, Guid userId)
		{
			using (var context = new CodeCampEntities())
			{
				MemberProfile existing =
					context.MemberProfiles.Include("Attachment").FirstOrDefault(p => p.UserId == userId);

				if (existing == null)
				{
					throw new ObjectNotFoundException("MemberPofile");
				}

				if (existing.Attachment != null)
				{
					existing.Attachment.Value = getBytes(photo);
					existing.Attachment.MimeType = photo.ContentType;
					existing.Attachment.Name = Path.GetFileName(photo.FileName);
				}
				else
				{
					// insert..
					var attachment = new Attachment
										{
											AttachmentID = Guid.NewGuid(),
											MimeType = photo.ContentType,
											Name = photo.FileName,
											Value = getBytes(photo)
										};
					existing.Attachment = attachment;
					context.AddToAttachments(attachment);
				}
				context.SaveChanges();
			}
		}


		public static List<MemberProfile> ListSpeakers()
		{
			using (var context = new CodeCampEntities())
			{
				var speakerQuery = from member in context.MemberProfiles.Include("Attachment").Include("Sessions")
								   where
								   member.Sessions.Any(s => s.Camp.StartDate > DateTime.Now)
									&& member.AllowPublicProfile
								   select member;
				return speakerQuery.ToList();
			}
		}


		#endregion

	}
}